package com.youpai.platform.pay.service.service.impl;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.AndroidPublisherScopes;
import com.google.api.services.androidpublisher.model.ProductPurchase;
import com.youpai.platform.common.enums.ProcessCodeEnum;
import com.youpai.platform.common.exceptions.BaseBizException;
import com.youpai.platform.common.util.StringUtils;
import com.youpai.platform.order.service.service.OrderService;
import com.youpai.platform.order.web.entity.dto.OrderDto;
import com.youpai.platform.order.web.entity.req.GetOrderReq;
import com.youpai.platform.pay.service.enums.AppPackageEnum;
import com.youpai.platform.pay.service.service.GooglePayCallBackService;
import com.youpai.platform.pay.web.entity.dto.GooglePayDTO;
import com.youpai.platform.pay.web.entity.resp.CheckGooglePayResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;

/**
 * @date: 2022/12/25
 * @author: Welles
 * @version: 1.0
 * @description: google支付回调service实现类
 */
@Slf4j
@Component
public class GooglePayCallBackServiceImpl implements GooglePayCallBackService {

    @javax.annotation.Resource
    private OrderService orderService;

    @Override
    public CheckGooglePayResp checkGooglePay(GooglePayDTO googlePayDTO) {
        CheckGooglePayResp resp = new CheckGooglePayResp();
        try {
            //使用服务帐户Json文件获取Google凭据
            List<String> scopes = new ArrayList<>();
            scopes.add(AndroidPublisherScopes.ANDROIDPUBLISHER);
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource("classpath:static/pc-api-9205604609199784266-176-ae6ba5a40ed7.json");
            GoogleCredential credential = GoogleCredential.fromStream(resource.getInputStream())
                    .createScoped(scopes);
            // TODO 关注这行代码
            credential.refreshToken();
            // 使用谷歌凭据和收据从谷歌获取购买信息
            HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            JacksonFactory jsonFactory = new JacksonFactory();
            AndroidPublisher publisher = new AndroidPublisher.Builder(httpTransport, jsonFactory, credential)
                    .setApplicationName("kila").build();
            AndroidPublisher.Purchases purchases = publisher.purchases();
            final AndroidPublisher.Purchases.Products.Get request = purchases.products().get(googlePayDTO.getPackageName(), googlePayDTO.getProductId(), googlePayDTO.getPurchaseToken());
            final ProductPurchase purchase = request.execute();
            if (null == purchase || StringUtils.isEmpty(purchase.getOrderId())) {
                resp.setMessage("支付失败");
                resp.setStatus(0);
                return resp;
            }
            GetOrderReq getOrderReq = new GetOrderReq();
            getOrderReq.setOrderId(purchase.getOrderId());
            getOrderReq.setUid("");
            OrderDto order = orderService.getOrder(getOrderReq);
            if (null == order) {
                resp.setMessage("支付成功");
                resp.setStatus(1);
                return resp;
            }
            resp.setStatus(0);
            resp.setMessage("订单不存在");
            return resp;
        } catch (Exception exception) {
            throw new BaseBizException(ProcessCodeEnum.MESSAGE_RECALL_OVERTIME);
        }

    }

    /**
     *
     *
     * @param appId   appId
     * @param orderId 订单id
     * @return 退款状态
     */
    public boolean refundOrder(int appId, String orderId) {
        try {
            String appPackage = AppPackageEnum.getAppPackageByAppId(appId);
            List<String> scopes = new ArrayList<>();
            scopes.add(AndroidPublisherScopes.ANDROIDPUBLISHER);
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource("classpath:static/pc-api-9205604609199784266-176-ae6ba5a40ed7.json");
            GoogleCredential credential = GoogleCredential.fromStream(resource.getInputStream())
                    .createScoped(scopes);
            // TODO 关注这行代码
            credential.refreshToken();
            // 使用谷歌凭据和收据从谷歌获取购买信息
            HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            JacksonFactory jsonFactory = new JacksonFactory();
            AndroidPublisher publisher = new AndroidPublisher.Builder(httpTransport, jsonFactory, credential)
                    .setApplicationName("kila").build();
            AndroidPublisher.Orders orders = publisher.orders();
            AndroidPublisher.Orders.Refund refund = orders.refund(appPackage, orderId);
            refund.execute();
        } catch (Exception exception) {
            log.error("退款失败！");
            return false;
        }
        return true;
    }
}
